import api from '@/api'
import consts from '@/const'
import { deepCopy, setPage } from '@/utils/util'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null,
        classIds: null,
        name: null,
        purpose: 'media'
    }
}

const state = {
    data: {
        mediaClasses: [],
        medias: []
    },
    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    mediaClasses: state => state.data.mediaClasses,
    medias: state => state.data.medias,
    mediaTotal: state => state.ui.page.total
}

// actions
const actions = {
    getMediaClasses({ commit }) {
        api.getClassifications('key_class_media', {
            loading: true,
            success: mediaClasses => {
                commit('setMediaClasses', { mediaClasses })
            }
        })
    },
    saveMediaClass({ dispatch }, data) {
        api.saveClassification(
            { ...data, classType: 'key_class_media' },
            {
                success: () => {
                    dispatch('getMediaClasses')
                }
            }
        )
    },
    removeMediaClass({ dispatch }, id) {
        api.removeClassification(id, {
            success: () => {
                dispatch('getMediaClasses')
            }
        })
    },
    getMedias({ commit }, { type, page, strategy }) {
        strategy = strategy ? strategy : 'media'
        const newPage = { strategy, ...(page ? page : state.ui.page) }
        api.getMedias(type, newPage, {
            loading: true,
            success: res => {
                const { pages, total } = res
                commit('setMediaPage', { pages, total })
                commit('setMedias', res)
            }
        })
    },
    saveMedia({ dispatch }, { type, data }) {
        api.saveMedia(type, data, {
            success: () => {
                dispatch('getMedias', { type, strategy: 'media' })
            }
        })
    },
    removeMedia({ dispatch }, { type, id }) {
        api.removeMedia(type, id, {
            success: () => {
                dispatch('getMedias', { type, strategy: 'media' })
            }
        })
    }
}

// mutations
const mutations = {
    setMediaClasses: (state, payload) => {
        state.data.mediaClasses = payload.mediaClasses
    },
    setMediaPage: (state, page) => {
        page && setPage(state.ui.page, page)
    },
    setMedias: (state, payload) => {
        state.data.medias = payload.content
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
